﻿// ==UserScript==
// @name           unpalatableFunt
// @namespace      org.i4qwee.unpalatableFunt
// @description    some unused script
// @include        http://funtiki.org/*
// ==/UserScript==

function createTextNode(w, label)
{
    return w.document.createTextNode(label);
}

function createCommentInfoField(w, commentInfoTd, nameField, label, marginTop, marginBottom)
{
    var mainDiv = createDiv(w);
    mainDiv.style.marginRight = '10px';
    mainDiv.style.marginTop = marginTop;
    mainDiv.style.marginBottom = marginBottom;
    commentInfoTd.appendChild(mainDiv);

    var textDiv = createDiv(w);
    textDiv.appendChild(createTextNode(w, label));
    textDiv.style.width = '150px';
    textDiv.style.marginBottom = '5px';
    mainDiv.appendChild(textDiv);

    mainDiv.appendChild(nameField);
}

function createCommentInfoFields(w, commentInfoTd, nameField, emailField, cityField)
{
    createCommentInfoField(w, commentInfoTd, nameField, 'Вас зовут:', '0px', '0px');
    createCommentInfoField(w, commentInfoTd, emailField, 'Ваш email:', '18px', '18px');
    createCommentInfoField(w, commentInfoTd, cityField, 'Ваш город:', '0px', '0px');
}

function createWrapperButton(w, wrapBy, useMargin)
{
    if (useMargin == undefined)
        useMargin = true;

    var buttonB = createUsualButton(w, useMargin);
    buttonB.innerHTML = '<' + wrapBy + '>' + wrapBy.toUpperCase() + '</' + wrapBy + '>';
    buttonB.addEventListener('click', createWrapperFunction(w, wrapBy));

    return buttonB;
}


function createWrapperFunction(w, wrapBy)
{
    var commentsTextArea = w.document.getElementById('form_content');

    return function()
    {
        if (!w.getSelection().anchorNode)
        {
            var sourceStr = commentsTextArea.value.substring(commentsTextArea.selectionStart, commentsTextArea.selectionEnd);

            insertIntoCommentTextArea(w, '<' + wrapBy + '>' + sourceStr + '</' + wrapBy + '>');
        }
    };
}

function createSubmitButton(w)
{
    var submitButton = w.document.createElement('button');
    submitButton.innerHTML = 'Отправить';
    submitButton.style.marginBottom = '5px';
//    submitButton.type = 'button';

    return submitButton;
}

function createButtonsDiv(w)
{
    var buttonsDiv = createDiv(w);
    buttonsDiv.style.marginTop = '10px';
    buttonsDiv.style.fontFamily = 'Trebuchet MS';
    return buttonsDiv;
}

function createNewCommentTable(w)
{
    var newCommentsTable = w.document.createElement('table');
    newCommentsTable.style.width = '100%';
    return newCommentsTable;
}

function createCommentInfoTd(w)
{
    var commentInfoTd = w.document.createElement('td');
    commentInfoTd.style.verticalAlign = 'top';
    return commentInfoTd;
}

function createCommentTd(w)
{
    var commentTd = w.document.createElement('td');
    commentTd.style.width = '100%';
    return commentTd;
}

function createUsualButton(w, useMargin, width)
{
    var usualButton = w.document.createElement('button');
    usualButton.type = 'button';

    if (width == undefined)
        usualButton.style.width = '20pt';
//    else
//        usualButton.style.width = width;

    if (useMargin)
        usualButton.style.marginLeft = '5px';

    return usualButton;
}

function createCiteButton(w)
{
    var citeButton = w.document.createElement('button');
    citeButton.type = 'button';
    citeButton.innerHTML = 'Цитировать&nbsp;выделенное';

    citeButton.addEventListener('click', function()
        {
            if (w.getSelection().toString())
                insertIntoCommentTextArea(w, '<blockquote>' + w.getSelection().toString() + '</blockquote>');
        });

    return citeButton;
}

function insertIntoCommentTextArea(w, text)
{
    var commentsTextArea = w.document.getElementById('form_content');

    commentsTextArea.value = commentsTextArea.value.substr(0, commentsTextArea.selectionStart) + text + commentsTextArea.value.substring(commentsTextArea.selectionEnd);
}

function createCiteDiv(w)
{
    var citeDiv = createDiv(w);
    citeDiv.style.cssFloat = 'right';
    return citeDiv;
}

function createSubmitDiv(w)
{
    var submitDiv = createDiv(w);
    submitDiv.style.cssFloat = 'left';
    return submitDiv;
}

function createWrapperButtonsDiv(w)
{
    var wrapperButtonsDiv = createDiv(w);
    wrapperButtonsDiv.style.cssFloat = 'left';
    wrapperButtonsDiv.style.clear = 'left';

    var buttonB = createWrapperButton(w, 'b', false);
    wrapperButtonsDiv.appendChild(buttonB);

    var buttonI = createWrapperButton(w, 'i');
    wrapperButtonsDiv.appendChild(buttonI);

    var buttonU = createWrapperButton(w, 'u');
    wrapperButtonsDiv.appendChild(buttonU);

    var buttonS = createWrapperButton(w, 's');
    wrapperButtonsDiv.appendChild(buttonS);
    return wrapperButtonsDiv;
}

function createButtonImg(w)
{
    var buttonImg = createUsualButton(w, false, false);
    buttonImg.innerHTML = 'img';

    buttonImg.addEventListener('click', function()
        {
            var imageLink = prompt("Ссылка на изображение");

            if(imageLink)
                insertIntoCommentTextArea(w, '<img src="' + imageLink + '" />');
        });

    return buttonImg;
}

function createButtonLink(w)
{
    var buttonLink = createUsualButton(w, true, false);
    buttonLink.innerHTML = 'link';

    buttonLink.addEventListener('click', function()
        {
            var link = prompt("Адрес ссылки");
            var linkText = prompt("Текст ссылки");

            if(link)
                insertIntoCommentTextArea(w, '<a href="' + link + '">' + linkText + '</a>');
        });
    
    return buttonLink;
}

function createInsertButtonsDiv(w)
{
    var insertButtonsDiv = createDiv(w);
    insertButtonsDiv.style.cssFloat = 'left';
    insertButtonsDiv.style.marginLeft = '20px';

    var buttonImg = createButtonImg(w);
    insertButtonsDiv.appendChild(buttonImg);

    var buttonLink = createButtonLink(w);
    insertButtonsDiv.appendChild(buttonLink);

    return insertButtonsDiv;
}

function createButtons(w, commentTd)
{
    var buttonsDiv = createButtonsDiv(w);
    commentTd.appendChild(buttonsDiv);

    var submitDiv = createSubmitDiv(w);
    buttonsDiv.appendChild(submitDiv);

    var submitButton = createSubmitButton(w);
    submitDiv.appendChild(submitButton);

    var citeDiv = createCiteDiv(w);
    buttonsDiv.appendChild(citeDiv);

    var citeButton = createCiteButton(w);
    citeDiv.appendChild(citeButton);

    var wrapperButtonsDiv = createWrapperButtonsDiv(w);
    buttonsDiv.appendChild(wrapperButtonsDiv);

    var insertButtonsDiv = createInsertButtonsDiv(w);
    buttonsDiv.appendChild(insertButtonsDiv);
}

function createEditor(w)
{
    var commentsDiv = w.document.getElementById('comment_form');
    var commentsForm = commentsDiv.getElementsByTagName('form')[0];
    var commentsTable = commentsDiv.getElementsByTagName('table')[0];
    var commentsTextArea = w.document.getElementById('form_content');
    var nameField = w.document.getElementsByName('name')[0];
    var emailField = w.document.getElementsByName('email')[0];
    var cityField = w.document.getElementsByName('city')[0];

    commentsForm.removeChild(commentsTable);

    var newCommentsTable = createNewCommentTable(w);
    commentsForm.appendChild(newCommentsTable);

    var mainCommentsRow = w.document.createElement('tr');
    newCommentsTable.appendChild(mainCommentsRow);

    var commentInfoTd = createCommentInfoTd(w);
    mainCommentsRow.appendChild(commentInfoTd);

    createCommentInfoFields(w, commentInfoTd, nameField, emailField, cityField);

    var commentTd = createCommentTd(w);
    mainCommentsRow.appendChild(commentTd);

    commentTd.appendChild(commentsTextArea);
    commentsTextArea.style.width = '100%';
    commentTd.innerHTML += '<br/>';

    createButtons(w, commentTd);
}

function setBodyColor(color)
{
    var bodyObj = document.getElementsByTagName('BODY')[0];
    bodyObj.style.backgroundColor = '#' + color;
}

function onBackColorChange(color)
{
    setBodyColor(color);

    setLongFuntCookie('backgroundColor', color);
}

function setLongFuntCookie(name, value)
{
    var expDate = new Date();
    expDate.setYear(2020);

    setCookie(name, value, expDate.toUTCString(), '/', 'funtiki.org');
}

function deleteCookie(name)
{
    var expDate = new Date();

    setCookie(name, '123', expDate.toUTCString());
}

function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie = name + "=" + value +
            ((expires) ? "; expires=" + expires : "") +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            ((secure) ? "; secure" : "");
}

function createDiv(w)
{
    return w.document.createElement('div');
}

function createPreferenceDiv(w)
{
    var prefDiv = createDiv(w);
    prefDiv.style.marginTop = prefDiv.style.marginBottom = '10px';
    prefDiv.style.clear = 'both';
    return prefDiv;
}

function appendColorDialogScript(w)
{
    var colorDialogSrc = w.document.createElement('script');
    colorDialogSrc.type = 'text/javascript';
    colorDialogSrc.src = 'http://jscolor.com/jscolor/jscolor.js';
    return colorDialogSrc;
}

function createColorChooser(w)
{
    var bodyColorChooser = w.document.createElement('input');
    bodyColorChooser.id = 'bodyColorChooser';
    bodyColorChooser.className = 'color';
    bodyColorChooser.style.border = '1px solid #6688AA';
    bodyColorChooser.style.fontSize = '13px';

    var savedColor = getCookie('backgroundColor');

    setBodyColor(savedColor);

    bodyColorChooser.value = savedColor;

    w.onBackColorChange = onBackColorChange;
    bodyColorChooser.setAttribute('onchange', 'onBackColorChange(this.color)');

    return bodyColorChooser;
}

function getCookie(name)
{
    var cookie = " " + document.cookie;
    var search = " " + name + "=";
    var setStr = null;
    var offset = 0;
    var end = 0;
    if (cookie.length > 0)
    {
        offset = cookie.indexOf(search);
        if (offset != -1)
        {
            offset += search.length;
            end = cookie.indexOf(";", offset)
            if (end == -1)
            {
                end = cookie.length;
            }
            setStr = cookie.substring(offset, end);
        }
    }
    return(setStr);
}

function createBackgroundColorLabel(w)
{
    var backgroundColorLabel = createDiv(w);
    backgroundColorLabel.style.cssFloat = 'left';
    backgroundColorLabel.appendChild(createTextNode(w, 'Цвет фона: '));
    return backgroundColorLabel;
}

function createColorSupport(w, prefDiv)
{
    var colorDialogSrc = appendColorDialogScript(w);
    prefDiv.appendChild(colorDialogSrc);

    var colorChooseDiv = createDiv(w);
    colorChooseDiv.style.cssFloat = 'left';
    prefDiv.appendChild(colorChooseDiv);

    var backgroundColorLabel = createBackgroundColorLabel(w);
    colorChooseDiv.appendChild(backgroundColorLabel);

    var bodyColorChooser = createColorChooser(w);
    colorChooseDiv.appendChild(bodyColorChooser);
}

function createOpenerFunction(commentNode, opener)
{
    return function()
        {
            try
                {
                    opener.style.display = 'none';
                    commentNode.style.display = 'block';
                }
                catch(e)
                {
                    console.log(e);
                }
        }
}

function createOpener(w, bannedUsername, commentNode)
{
    var opener = w.document.createElement('a');
    opener.href = '#noway';
    opener.innerHTML = 'Здесь был комментарий от ' + bannedUsername + '. Может посмотрим, что он написал?';

    opener.addEventListener('click', createOpenerFunction(commentNode, opener));
    return opener;
}

function isFromBanned(node, bannedUsernames)
{
    for (var i = 0; i < bannedUsernames.length; i++)
    {
        var banned = bannedUsernames[i];

        if(node.tagName == 'DIV' && node.innerHTML.search('<div><b>[0-9]+. ' + banned + '</b>') > -1)
            return banned;
    }

    return null;
}

function checkCommentsForBanned(bannedUsernames, w)
{
    var voteDiv = w.document.getElementById('vote');
    var centerDiv = voteDiv.parentNode;

    var bannedUsername;

    try
    {
        for each (var node in centerDiv.childNodes)
        {
            if(node.childNodes == null)
                continue;

            var commentNode = node.childNodes[3];

            if (bannedUsername = isFromBanned(node, bannedUsernames))
            {
                commentNode.style.display = 'none';

                var openerDiv = createDiv(w);
                openerDiv.style.marginTop = openerDiv.style.marginBottom = '5px';

                var opener = createOpener(w, bannedUsername, commentNode);
                openerDiv.appendChild(opener);
                node.insertBefore(openerDiv, commentNode);
            }
        }
    } catch(e)
    {
        console.log(e);
    }
}

function createBannedUserButton(w, bannedUser, bannedUsers)
{
    var bannedUserDiv = createDiv(w);
    bannedUserDiv.style.cssFloat = 'left';
    bannedUserDiv.style.marginLeft = '5px';
    bannedUserDiv.style.border = '1px solid #6688AA';
    bannedUserDiv.style.borderRadius = '10px';

    var bannedUserNameDiv = createDiv(w);
    bannedUserNameDiv.style.cssFloat = 'left';
    bannedUserNameDiv.style.paddingLeft = bannedUserNameDiv.style.paddingRight = '5px';
    bannedUserNameDiv.appendChild(createTextNode(w, bannedUser));
    bannedUserDiv.appendChild(bannedUserNameDiv);

    var deleteBannedUserDiv = createDiv(w);
    deleteBannedUserDiv.style.cursor = 'pointer';
    deleteBannedUserDiv.style.width = '15px';
    deleteBannedUserDiv.style.border = '1px solid #6688AA';
    deleteBannedUserDiv.style.cssFloat = 'left';
    deleteBannedUserDiv.style.textAlign = 'center';
    deleteBannedUserDiv.style.borderRadius = '10px';
    deleteBannedUserDiv.appendChild(createTextNode(w, 'X'));

    deleteBannedUserDiv.addEventListener('click', createDeleteBannedUserDivFunction(bannedUserDiv, bannedUser, bannedUsers));

    bannedUserDiv.appendChild(deleteBannedUserDiv);
    return bannedUserDiv;
}

function createDivsForBannedUsers(bannedUsers, preferencesDiv, w)
{
    var bannedUsersDiv = createDiv(w);
    bannedUsersDiv.style.cssFloat = 'left';
    preferencesDiv.appendChild(bannedUsersDiv);

    var bannedLabelDiv = createDiv(w);
    bannedLabelDiv.style.cssFloat = 'left';
    bannedLabelDiv.style.marginLeft = '10px';
    bannedLabelDiv.appendChild(createTextNode(w, 'Забаненные:'));
    bannedUsersDiv.appendChild(bannedLabelDiv);

    if (bannedUsers.length > 0 && bannedUsers[0])
    {
        for (var i = 0; i < bannedUsers.length; i++)
        {
            var bannedUser = bannedUsers[i];

            var bannedUserDiv = createBannedUserButton(w, bannedUser, bannedUsers);
            bannedUsersDiv.appendChild(bannedUserDiv);
        }
    }

    var addNewBannedUserDiv = createDiv(w);
    addNewBannedUserDiv.id = 'adder';
    addNewBannedUserDiv.style.marginLeft = addNewBannedUserDiv.style.marginRight = '5px';
    addNewBannedUserDiv.style.cursor = 'pointer';
    addNewBannedUserDiv.style.border = '1px dashed #6688AA';
    addNewBannedUserDiv.style.borderRadius = '10px';
    addNewBannedUserDiv.style.cssFloat = 'left';
    addNewBannedUserDiv.appendChild(createTextNode(w, '+Ещё один!'));
    bannedUsersDiv.appendChild(addNewBannedUserDiv);

    addNewBannedUserDiv.addEventListener('click', createAddNewBannedUserFunction(w, bannedUsersDiv, bannedUsers));
}

function createAddNewBannedUserFunction(w, bannedUsersDiv, bannedUsers)
{
    return function()
    {
        var bannedUsername = prompt('Имя забаненного: ');

        if (bannedUsername)
        {
            var bannedUserDiv = createBannedUserButton(w, bannedUsername, bannedUsers);

            var i = 0;

            for (i = 0; i < bannedUsersDiv.childNodes.length; i++)
            {
                var node = bannedUsersDiv.childNodes[i];

                if (node.id == 'adder')
                    break;
            }

            bannedUsersDiv.insertBefore(bannedUserDiv, bannedUsersDiv.childNodes[i]);

            bannedUsers.push(bannedUsername);
            checkCommentsForBanned(bannedUsers, w);

            saveBannedUsers(bannedUsers);
        }
    }
}

function saveBannedUsers(bannedUsers)
{
    if(bannedUsers == null)
        return;

    var cookie = "";

    for each (var bannedUser in bannedUsers)
    {
        cookie += encodeURI(bannedUser) + ", ";
    }

    cookie = cookie.slice(0, -2);

    setLongFuntCookie("bannedUsers", cookie);
}

function createDeleteBannedUserDivFunction(bannedUserDiv, bannedUsername, bannedUsers)
{
    return function()
    {
        bannedUserDiv.style.display = 'none';

        for (var i = 0; i < bannedUsers.length; i++)
        {
            var username = bannedUsers[i];

            if(username == bannedUsername)
            {
                bannedUsers.splice(i, 1);
                saveBannedUsers(bannedUsers);
                break;
            }
        }
    }
}

function loadBannedUsernames()
{
    var cookie = getCookie("bannedUsers");

    var bannedUsers = cookie.split(", ");

    for (var i = 0; i < bannedUsers.length; i++)
    {
        bannedUsers[i] = decodeURI(bannedUsers[i]);
    }

    return bannedUsers;
}

(function(window, undefined)
{
    var w;

    if (typeof unsafeWindow != undefined)
    {
        w = unsafeWindow
    } else
    {
        w = window;
    }

    if (w.self != w.top)
    {
        return;
    }

    if (/http:\/\/funtiki.org/.test(w.location.href))
    {
        var voteDiv = w.document.getElementById('vote');
        var centerDiv = voteDiv.parentNode;

        var bannedUsernames = loadBannedUsernames();

        checkCommentsForBanned(bannedUsernames, w);

        var spacerDiv = createDiv(w);
        spacerDiv.style.height = '30px';
        centerDiv.insertBefore(spacerDiv, centerDiv.childNodes[4]);

        var prefDiv = createPreferenceDiv(w);
        centerDiv.insertBefore(prefDiv, centerDiv.childNodes[4]);

        createColorSupport(w, prefDiv);

        if (w.location.href.search('book') > -1)
        {
            createDivsForBannedUsers(bannedUsernames, prefDiv, w);
        }

        createEditor(w);
    }
})(window);